package com.webserver.core;

import com.webserver.annotations.Controller;
import com.webserver.annotations.RequestMapping;

import java.io.File;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

public class HandlerMapping {
    private static Map<String, Method> mapping = new HashMap<>();

    static {
        initMapping();
    }

    private static void initMapping() {
        try {
            //定位启动当前Boot的启动类所在的目录
            File rootDir = new File(
                    BirdBootApplication.primarySource.getResource(".").toURI()
            );
            //定位controller包
            File dir = new File(rootDir, "controller");
            if (dir.exists()) {
                File[] subs = dir.listFiles(f -> f.getName().endsWith(".class"));
                for (File sub : subs) {
                    String className = sub.getName().replace(".class", "");
                    //启动类所在的包
                    String packageName = BirdBootApplication.primarySource.getPackage().getName();
                    Class cls = Class.forName(packageName + ".controller." + className);
                    if (cls.isAnnotationPresent(Controller.class)) {
                        Method[] methods = cls.getDeclaredMethods();
                        for (Method method : methods) {
                            if (method.isAnnotationPresent(RequestMapping.class)) {
                                RequestMapping rm = method.getAnnotation(RequestMapping.class);
                                String value = rm.value();
                                mapping.put(value, method);
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static Method getMethod(String uri){
        return mapping.get(uri);
    }

    public static void main(String[] args) {
        System.out.println(mapping.size());
        System.out.println(mapping);
    }
}